<template>
  <v-layout :title="(id?'修改':'创建')+'开票单'">

    <orderList
      :right-data.sync="rightData"
      :right-title="rightTitle"
      :table-title="tableTitle"
      :total-money1.sync="totalMoney"
      :invoice="true"
      @next1="next1"
      :to-order.sync="toOrder"
    />

    <el-collapse-transition>
      <el-row v-if="orderSelected||id">
        <div class="subtitle">
          开票信息选择
        </div>
        <el-card>
          <el-row class="clearfix pdt15 confirm" type="flex" justify="center">
            <el-col :lg="14" :md="14" :sm="20" :xs="24">
              <el-form label-width="120px" size="mini">
                <el-form-item label="微赞公司: ">
                  <el-select
                    v-model="confirmData.company_type"
                    filterable
                    style="width:50%;">
                    <el-option
                      v-for="item in weizanList"
                      :label="item.label"
                      :value="item.value"
                      :key="item.label"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="开票公司: ">
                  <el-select
                    v-model="confirmData.invoiceInfo_id"
                    filterable
                    style="width:50%;"
                    @change="companyChanged">
                    <el-option
                      v-for="item in companyList"
                      :label="item.label"
                      :value="item.value"
                      :key="item.label"/>
                  </el-select>
                  <el-button type="primary" @click="createInvoiceCompany">
                    新增开票公司
                  </el-button>
                </el-form-item>
              </el-form>
              <el-card>
                <v-form
                  :form-title="confirmTitle"
                  :form-data="confirmData"
                  label-width="120px"
                >
                  <template v-for="item in 5" slot-scope="props" :slot="'upload'+item">
                    <uploadPdf
                      :props="props"
                      :show-upload="item===5"
                      :show-del="item===5"
                      :formData="confirmData"
                      @del="delFile"
                    />
                  </template>

                </v-form>
              </el-card>

              <el-card v-if="invoiceComplete" class="mt15">
                <el-form label-width="120px" size="mini">
                  <el-form-item label="合同编号">
                    <el-input v-model="confirmData.contract_num"/>
                  </el-form-item>
                  <el-form-item label="开票编号">
                    <el-input
                      v-model="confirmData.invoice_code"
                      :disabled="!admin&&!assistantRole&&!financeRole"
                    />
                  </el-form-item>
                  <el-form-item label="开票时间">
                    <el-date-picker
                      v-model="confirmData.invoice_date"
                      type="date"
                      value-format="yyyy-MM-dd"
                      :disabled="!admin&&!assistantRole&&!financeRole"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                  <!--<el-form-item label="发票电子档">-->
                    <!--<el-upload-->
                      <!--:action="previewUrl"-->
                      <!--:with-credentials="true"-->
                      <!--:on-success="handleSuccess"-->
                      <!--:on-error="onError"-->
                      <!--:on-remove="onRemove"-->
                      <!--:on-preview="onPreview"-->
                      <!--:disabled=" !(admin||assistantRole||financeRole)"-->
                      <!--multiple-->
                      <!--:file-list="fileList"-->
                    <!--&gt;-->
                      <!--<el-button size="small" :disabled=" !(admin||assistantRole||financeRole)" type="primary">点击上传-->
                      <!--</el-button>-->
                    <!--</el-upload>-->
                  <!--</el-form-item>-->
                </el-form>
              </el-card>
              <el-row type="flex" justify="end" class="pdt15" v-if="admin||businessRole">
                <el-button type="primary" size="small" @click="submit(4)">商务提交审核</el-button>
              </el-row>
              <el-row type="flex" justify="end" class="pdt15" v-if="assistantRole||financeRole||admin">
                <el-button type="primary" size="small" @click="submit(5)">财务审核通过</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-row>
    </el-collapse-transition>
  </v-layout>
</template>

<script>
  import auth from '@/mixins/auth'
  import orderList from '../components/order_list'
  import uploadPdf from '../../components/uploadPdf'
  import {mapGetters} from 'vuex'

  export default {
    components: {
      orderList,
      uploadPdf
    },
    mixins: [auth],
    data() {
      return {
        fileList: [],
        previewUrl: process.env.BASE_API + 'file/up',
        id: '',
        totalMoney: 0,
        orderSelected: false,

        time: [],
        tableTitle: [
          {
            cn: 'id',
            en: 'ad_id'
          },
          {
            cn: '公众号',
            en: 'name'
          },
          {
            cn: '广告主',
            en: 'ad_name'
          },
          {
            cn: '订单金额',
            en: 'ad_price'
          },
          {
            cn: '商务负责人',
            en: 'swname'
          },
          {
            cn: '时间',
            en: 'publish_at'
          }
        ],
        rightTitle: [
          {
            cn: 'id',
            en: 'ad_id'
          },
          {
            cn: '公众号',
            en: 'name'
          },
          {
            cn: '订单金额',
            en: 'ad_price'
          },
          {
            cn: '时间',
            en: 'publish_at'
          }
        ],
        rightData: [],

        companyData: 0,
        companyList: [],
        weizanList: [
          {
            label: '霍尔果斯微赞网络科技有限公司',
            value: 1
          },
          {
            label: '霍尔果斯微赞网络科技有限公司杭州第一分公司',
            value: 0
          },
        ],
        invoiceCompanyList: [],

        confirmTitle: [
          {
            cn: '纳税人识别号: ',
            en: '纳税人识别号',
            disabled: true
          },
          {
            cn: '公司地址: ',
            en: 'address',
            disabled: true
          },
          {
            cn: '电话: ',
            en: 'tel',
            disabled: true
          },
          {
            cn: '开户行 ',
            en: '开户行',
            disabled: true
          },
          {
            cn: '账号 ',
            en: '帐号',
            disabled: true
          },
          {
            cn: '发票类别: ',
            en: 'invoice_type',
            type: 'select',
            list: [
              {
                label: '专票',
                value: '1'
              },
              {
                label: '普票',
                value: '2'
              }
            ],
            disabled: true
          },
          {
            cn: '开票内容: ',
            en: 'invoice_content',
            type: 'select',
            list: [
              {
                label: '广告费',
                value: '1'
              },
              {
                label: '广告发布费',
                value: '2'
              },
              {
                label: '信息服务费',
                value: '3'
              },
              {
                label: '信息技术服务费',
                value: '4'
              },
              {
                label: '服务费',
                value: '5'
              }
            ],
            disabled: true,
          },
          {
            cn: '营业执照: ',
            en: 'business_license',
            disabled: true,
            info: '营业执照.pdf',
            url: 'https://tuitui.wxtt.cn/storage/image',
            type: 'upload1'
          },
          {
            cn: '开户许可 ',
            en: 'opening_permit',
            info: '开户许可.pdf',
            type: 'upload2',
            url: 'https://tuitui.wxtt.cn/storage/image'
          },
          {
            cn: '纳税人证明 ',
            en: '一般纳税人证明',
            info: '纳税人证明.pdf',
            type: 'upload3',
            url: 'https://tuitui.wxtt.cn/storage/upload'
          },
          {
            cn: '开票资料 ',
            en: 'invoice_infrom',
            info: '开票资料.pdf',
            type: 'upload4',
            url: 'https://tuitui.wxtt.cn/storage/upload'
          },
          {
            cn: '结算单: ',
            en: 'invoice_file',
            info: '结算单.pdf',
            type: 'upload5',
            url: 'https://tuitui.wxtt.cn/storage/upload'
          },
          {
            cn: '备注: ',
            en: 'remark',
            type: 'textarea',
            url: 'https://tuitui.wxtt.cn/storage/upload'
          }
        ],
        confirmData: {},

        invoiced_infos: {},

        toOrder: false,
      }
    },
    computed: {
      ...mapGetters([
        'name'
      ]),
      invoiceComplete() {
        return this.confirmData.cur_status >= 5
      },
      contrastNameCheck() {
        if (this.rightData.length) {
          const check = false
          // console.log(this.rightData[0].contract_name, this.confirmData.开票公司名称,2323);
          return this.rightData[0].contract_name && this.rightData[0].contract_name === this.confirmData.开票公司名称
        }
      },
      fans_id() {
        return this.rightData.length && this.rightData[0].fans_id
      },
      submitable() {
        return (this.rightData.length > 0 && this.confirmData.id)
      }
    },
    activated() {
      this.id = this.$route.query.id
      // debugger
      if (!this.id && !this.toOrder) {
        this.rightData = []
      } else {
        this.toOrder = false
      }
      // 获取开票公司列表
      if (this.id) {
        this.getInvoiceDetail()
      }
      this.getCompanyList()
    },
    watch:{
      rightData(val){
        if (val.length) {
          this.confirmData.contract_num = this.rightData[0].contract_num
        }
      }
    },
    methods: {
      // 获取开票公司列表
      getCompanyList() {
        // let data = {id:this.fans_id};
        this.$post('action/InvoiceInformation/find')
          .then(res => {
            this.companyList = res.data.map(item => {
              item.company_name = item.开票公司名称
              item.address = item.公司地址
              item.tel = item.电话
              item.invoice_type = item.发票类别
              item.business_license = item.营业执照
              item.taxpayer_cer = item.纳税人证明
              const obj = {}
              obj.label = item.company_name
              obj.value = item.id
              return obj
            })
            this.invoiceCompanyList = res.data
          })
      },

      companyChanged(val) {
        this.invoiceCompanyList.forEach((item, index) => {
          if (item.id === val) {
            // this.confirmData = item;
            this.confirmData = {...this.confirmData, ...item}
          }
        })
      },

      // 获取详情
      getInvoiceDetail() {
        const data = {reqid: this.id}
        this.$get('action/InvoiceRequisition/qryOp', data)
          .then(res => {
            this.confirmData = {...res.data.InvoiceInformation[0], ...res.data.Invoice} || []
            // this.messages = res.data.Log;
            // this.invoiceCompanyList = res.data.
            this.confirmData.invoiceInfo_id = this.confirmData.invoiceinfo_id
            this.fileList = this.confirmData.invoice_electronic ? JSON.parse(this.confirmData.invoice_electronic) : []
            this.rightData = res.data.adsList.map(item => {
              const data = item
              data.rest_money = +data.ad_price - data.real_price
              if (data.money) {
                return data
              }
              data.money = data.rest_money
              return data
            })

            this.confirmData.contract_num = res.data.adsList.length?res.data.adsList[0].contract_num:''
          })
          .catch(err => {
            console.log(err)
            this.$router.go(-1)
          })
      },

      createInvoiceCompany() {
        this.$router.push({
          name: 'invoice_info.modify'
        })
      },

      submit(val) {
        if (!this.submitable) {
          return this.$alert('请先选择订单和开票公司', '提示', {
            confirmButtonText: '确定'
          })
        } else {
          const url = this.id ? 'action/InvoiceRequisition/update' : 'action/InvoiceRequisition/save'

          if (this.confirmData.cur_status >= 6) {

            const invoice_electronic = this.fileList.map(item => {
              let obj = {};
              obj.name = item.name;
              obj.url = item.response ? item.response.url : item.url;
              return obj
            })
            this.confirmData.invoice_electronic = JSON.stringify(invoice_electronic)
          }
          const arrAdvsId = this.rightData.map(item => {
            return item.ad_id
          }).join(',')

          const cur_status = this.confirmData.cur_status === 7 ? 7 : (val===4?4:((this.confirmData.cur_status + 1) || val));
          if (cur_status === 6 && !this.confirmData.invoice_code) {
            return (
              this.$alert('请填写开票编号', '提示', {
                confirmButtonText: '确定',
              })
            )
          }
          const data = {
            ...this.confirmData,
            swname: this.rightData.length && this.rightData[0].swname,
            swid: this.rightData.length && this.rightData[0].swid,
            create_name: this.name,
            money: this.totalMoney,
            arrAdvsId,
            ...this.invoiced_infos,
            invoice_code: this.confirmData.invoice_code,
            id: this.reqid,
            cur_status,
          }
          const datas = this.id ? {...data, id: this.id} : {...data}
          this.$post(url, datas)
            .then(res => {
              new Promise((resolve, reject) => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                resolve()
              }).then(_ => {
                this.$router.push({
                  name: 'invoice_manage.check'
                })
              })
            })
        }
      },

      next1() {
        this.orderSelected = true
        // this.selectData = this.rightData
      },
      delFile(props) {
        this.$set(this.confirmData, props.info.en, '')
      },
      handleSuccess(res, file, fileList) {
        this.fileList = fileList
      },
      onError(err) {
        console.log(err);
      },
      onRemove(file, fileList) {
        this.fileList = fileList
      },
      onPreview(file) {
        window.open(file.url)
      }
    }
  }
</script>
